CLru
Another LRU cache implementation in rust. It has two main characteristics that differentiates it from other implementation:
-
It is backed by a HashMap: it offers a O(1) time complexity (amortized average) for common operations like:
get
/get_mut
put
/pop
peek
/peek_mut
-
It is a weighted cache: each key-value pair has a weight and the capacity serves as both as:
- a limit to the number of elements
- and as a limit to the total weight of its elements
using the following formula:
Even though most operations don't depend on the number of elements in the cache,
CLruCache::put_with_weight
has a special behavior: because it needs to make room
for the new element, it will remove enough least recently used elements. In the worst
case, that will require to fully empty the cache. Additionally, if the weight of the
new element is too big, the insertion can fail.
For the common case of an LRU cache whose elements don't have a weight, a default
ZeroWeightScale
is provided and unlocks some useful APIs like:
CLruCache::put
: an infallible insertion that will remove a maximum of 1 element.CLruCache::put_or_modify
: a conditional insertion or modification flow similar to the entry API of [HashMap
].CLruCache::try_put_or_modify
: fallible version ofCLruCache::put_or_modify
.- All APIs that allow to retrieve a mutable reference to a value (e.g.:
CLruCache::get_mut
).
Disclaimer
Most of the API, documentation, examples and tests have been heavily inspired by the lru crate. I want to thank jeromefroe for his work without which this crate would have probably never has been released.
Differences with lru
The main differences are:
- Smaller amount of unsafe code. Unsafe code is not bad in itself as long as it is thoroughly reviewed and understood but can be surprisingly hard to get right. Reducing the amount of unsafe code should hopefully reduce bugs or undefined behaviors.
- API closer to the standard HashMap collection which allows to lookup with
Borrow
-ed version of the key.
Example
Below are simple examples of how to instantiate and use this LRU cache.
Using the default ZeroWeightScale
:
use NonZeroUsize;
use CLruCache;
let mut cache = new;
cache.put;
cache.put;
assert_eq!;
assert_eq!;
assert!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert!;
assert_eq!;
Using a custom WeightScale
implementation:
use NonZeroUsize;
use ;
;
let mut cache = with_config;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
Tests
Each contribution is tested with regular compiler, miri, and 4 flavors of sanitizer (address, memory, thread and leak). This should help catch bugs sooner than later.
TODO
- improve documentation and add examples